	
********************************************************************************
*** Time shifts for synthetic controls
** Robustness: Forward Shift Only -- Lags and No Leads
cd /disk/agedisk3/medicare.work/poterba-DUA52260/jetson-dua52260/outliers/synth/100pct/robustness/forwardonly
use types_panel.dta, clear

*********************************************************************
*** Fit Outliers on various lags to find best fit  
levelsof group, local(levels)
keep group dt pmt_amt 
reshape wide pmt_amt, i(dt) j(group)
tsset dt
matrix distanceLag = (0,0,0)
** No leads

set matsize 11000

** Only want to keep outliers pre-period 
local treatment_period = mofd(mdy(11, 4, 2002))
replace pmt_amt999 = . if dt >= `treatment_period'

** Find max lag so that there are 3 years of pre-period data 
summarize dt 
local maxlag = `treatment_period' - r(min) - 36
	** Treatment period - min  = length of end window 
	** Take 60 off and that's the max you can shift before running out of data


gen diff = 0 
*** Loop, storing leads lags and fit
foreach g of local levels {
	disp `g'
	* Skip Outlier treated group
	if `g' == 999{
			continue
		}

	foreach t of numlist 0/`maxlag'{
		*disp `t'
		qui replace diff =  (pmt_amt999 - L`t'.pmt_amt`g')^2
		qui summarize diff 
		matrix distanceLag = (distanceLag \ `g', `t', r(sum)/r(N))
		}

}

svmat distanceLag
keep distanceLag*

rename distanceLag1 laggroup
rename distanceLag2 lagperiod
rename distanceLag3 lagdistance

drop if laggroup == 0
save distancelag.dta, replace

********************************************************************************
*** Find best fit per group

cd /disk/agedisk3/medicare.work/poterba-DUA52260/jetson-dua52260/outliers/synth/100pct/robustness/forwardonly
use distancelag.dta, clear

* Create best fit per group
keep laggroup lagperiod lagdistance
drop if mi(laggroup)
bysort laggroup: egen minlagdistance = min(lagdistance)
keep if lagdistance == minlagdistance
drop minlagdistance

* Prep for merge 
rename laggroup group
rename lagdistance mindistance
replace lagperiod = -1*lagperiod
rename lagperiod period 
save groupleadlags.dta, replace



********************************************************************************





